package com.ukefu.webim.service.es;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.util.WorkOrdersUtils;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.WorkOrders;

@Component
public class OrdersCommentRepositoryImpl implements OrdersCommentEsCommonRepository{
	@Autowired
	private UserRepository userRes ;
	
	@Autowired
	private ContactsRepository contactsRes ;
	
	private ElasticsearchTemplate elasticsearchTemplate;

	@Autowired
	public void setElasticsearchTemplate(ElasticsearchTemplate elasticsearchTemplate) {
		this.elasticsearchTemplate = elasticsearchTemplate;
    }

	@Override
	public Page<OrdersComment> findByQuery(BoolQueryBuilder boolQueryBuilder, String q , Pageable page) {
		
		if(!StringUtils.isBlank(q)){
	    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
	    }
		return processQuery(boolQueryBuilder , page);
	}
	
	private Page<OrdersComment> processQuery(BoolQueryBuilder boolQueryBuilder, Pageable page){
		NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC)).withSort(new FieldSortBuilder("name").unmappedType("string").order(SortOrder.DESC));
		
		searchQueryBuilder.withPageable(page) ;
		searchQueryBuilder.withHighlightFields(new HighlightBuilder.Field("title").fragmentSize(200)) ;
		
		Page<OrdersComment> ordersCommentList = null ;
		if(elasticsearchTemplate.indexExists(WorkOrders.class)){
			ordersCommentList = elasticsearchTemplate.queryForPage(searchQueryBuilder.build() , OrdersComment.class , new UKResultMapper()) ;
		}
		if(ordersCommentList.getContent().size() > 0){
			WorkOrdersUtils.processOrdersComment(ordersCommentList.getContent() , userRes , contactsRes) ;
			
		}
		return ordersCommentList;
	}
	
	@Override
	public Page<OrdersComment> findByQuery(BoolQueryBuilder boolQueryBuilder, Pageable page) {
		// TODO Auto-generated method stub
		return this.processQuery(boolQueryBuilder, page);
	}
}
